package cn.gztang.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author GaoFeng2017
 * @date 2018/8/12 9:58
 */
public class CharsetEncodingFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(CharsetEncodingFilter.class);
    private static String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding = filterConfig.getInitParameter("encoding");
        if (encoding != null) {
            CharsetEncodingFilter.encoding = encoding;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        logger.info("编码集,{},{}",request.getCharacterEncoding(),response.getCharacterEncoding());
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=" + encoding);

        request = new RequestWrapper(request);
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }

    private static class RequestWrapper extends HttpServletRequestWrapper {


        public RequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);

            if (value == null) {
                return null;
            }

            try {
                if ("GET".equalsIgnoreCase(this.getMethod())) {
                    return new String(value.getBytes("ISO-8859-1"),encoding);
                }
            } catch (UnsupportedEncodingException e) {
                return null;
            }

            return  value;
        }
    }
}
